package com.ruoyi.cderp.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.cderp.domain.*;
import com.ruoyi.cderp.domain.Properties;
import com.ruoyi.cderp.mapper.PropertiesMapper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.cderp.mapper.ProductInfoMapper;
import com.ruoyi.cderp.service.IProductInfoService;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 商品Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-13
 */
@Service
public class ProductInfoServiceImpl implements IProductInfoService
{
    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Autowired
    private PropertiesMapper propertiesMapper;

    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public ProductInfo selectProductInfoById(String id)
    {
        // 1. 按属性ID分组
        Map<String, List<Properties>> groupedProperties = propertiesMapper.selectPropertiesList(id).stream()
                .collect(Collectors.groupingBy(Properties::getPropertyId));

        // 2. 合并每组属性
        List<Properties> mergedProperties = new ArrayList<>();
        groupedProperties.forEach((pid, props) -> {
                    Properties dto = new Properties();
                    dto.setPropertyId(pid);
                    dto.setPropertyName(props.get(0).getPropertyName()); // 属性名相同，取第一个

                    // 拼接text和textStr（多值用逗号分隔）
                    String mergedText = props.stream()
                            .map(Properties::getPropertyItemId)
                            .collect(Collectors.joining(","));
                    String mergedTextStr = props.stream()
                            .map(Properties::getPropertyText)
                            .collect(Collectors.joining("，")); // 中文逗号
                    dto.setPropertyItemId(mergedText);
                    dto.setPropertyText(mergedTextStr);
                    mergedProperties.add(dto);
        });

        ProductInfo printInfo =  productInfoMapper.selectProductInfoById(id);
        if(printInfo!=null){
            printInfo.setProperties(mergedProperties);
        }
        return printInfo;
    }

    /**
     * 查询商品列表
     *
     * @param productInfo 商品
     * @return 商品
     */
    @Override
    public List<ProductInfo> selectProductInfoList(ProductInfo productInfo)
    {
        return productInfoMapper.selectProductInfoList(productInfo);
    }

    /**
     * 新增商品
     *
     * @param productInfo 商品
     * @return 结果
     */
    @Transactional
    @Override
    public int insertProductInfo(ProductInfo productInfo)
    {
        //随机生成商品编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String formattedDate = sdf.format(new Date());
        Random random = new Random();
        int randomNumber = 10000000 + random.nextInt(90000000); // 生成8位数随机数
        productInfo.setId("187" + formattedDate+randomNumber);

        productInfo.setCreateTime(DateUtils.getNowDate());
        // 获取当前登录用户对象
        LoginUser loginUser = SecurityUtils.getLoginUser();

        //创建人编号
        productInfo.setCreateById(loginUser.getUser().getUserId().toString());
        //创建人名称
        productInfo.setCreateBy(loginUser.getUser().getUserName());

        int num = productInfoMapper.insertProductInfo(productInfo);

        if(StringUtils.isNotNull(productInfo.getBaseDataProductBundleList())){
            //调用新增组合商品信息
            insertBaseDataProductBundle(productInfo);
        }

        //判断是否有采购价，有则修改
        if (StringUtils.isNotNull(productInfo.getPurchasePrice())){
            Purchase purchase = new Purchase();
            purchase.setId(productInfo.getId());
            purchase.setPrice(productInfo.getPurchasePrice());
            productInfoMapper.insertPurchase(purchase);
        }
        if (StringUtils.isNotNull(productInfo.getSalePrice())){
            ProductSale productSale = new ProductSale();
            productSale.setId(productInfo.getId());
            productSale.setPrice(productInfo.getSalePrice());
            productInfoMapper.insertProductSale(productSale);
        }
        if (StringUtils.isNotNull(productInfo.getRetailPrice())){
            ProductRetail productRetail = new ProductRetail();
            productRetail.setId(productInfo.getId());
            productRetail.setPrice(productInfo.getRetailPrice());
            productInfoMapper.insertProductRetail(productRetail);
        }

        return num;
    }



    /**
     * 修改商品
     *
     * @param productInfo 商品
     * @return 结果
     */
    @Transactional
    @Override
    public int updateProductInfo(ProductInfo productInfo)
    {
        productInfo.setUpdateTime(DateUtils.getNowDate());
        // 获取当前登录用户对象
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //修改人编号
        productInfo.setUpdateById(loginUser.getUser().getUserId().toString());
        //修改人名称
        productInfo.setUpdateBy(loginUser.getUser().getUserName());

        //批量删除商品组合表信息
        productInfoMapper.deleteBaseDataProductBundleByMainProductId(productInfo.getId());
        //新增组合商品信息
        insertBaseDataProductBundle(productInfo);

        //判断是否有采购价，有则修改
        if (productInfo.getPurchasePrice()!=null){
            Purchase purchase = new Purchase();
            purchase.setId(productInfo.getId());
            purchase.setPrice(productInfo.getPurchasePrice());
            productInfoMapper.updatePurchase(purchase);
        }
        if (productInfo.getSalePrice()!=null){
            ProductSale productSale = new ProductSale();
            productSale.setId(productInfo.getId());
            productSale.setPrice(productInfo.getSalePrice());
            productInfoMapper.updateProductSale(productSale);
        }
        if (productInfo.getRetailPrice()!=null){
            ProductRetail productRetail = new ProductRetail();
            productRetail.setId(productInfo.getId());
            productRetail.setPrice(productInfo.getRetailPrice());
            productInfoMapper.updateProductRetail(productRetail);
        }
        return productInfoMapper.updateProductInfo(productInfo);
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProductInfoByIds(String[] ids)
    {
        productInfoMapper.deleteBaseDataProductBundleByMainProductIds(ids);
        return productInfoMapper.deleteProductInfoByIds(ids);
    }

    /**
     * 删除商品信息
     *
     * @param id 商品主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProductInfoById(String id)
    {
        productInfoMapper.deleteBaseDataProductBundleByMainProductId(id);
        return productInfoMapper.deleteProductInfoById(id);
    }

    @Override
    public int insertPurchase(Purchase purchase) {
        return productInfoMapper.insertPurchase(purchase);
    }

    @Override
    public int updatePurchase(Purchase purchase) {
        return productInfoMapper.updatePurchase(purchase);
    }

    @Override
    public int insertProductSale(ProductSale productSale) {
        return productInfoMapper.insertProductSale(productSale);
    }

    @Override
    public int updateProductSale(ProductSale productSale) {
        return productInfoMapper.updateProductSale(productSale);
    }

    @Override
    public int insertProductRetail(ProductRetail productRetail) {
        return productInfoMapper.insertProductRetail(productRetail);
    }

    @Override
    public int updateProductRetail(ProductRetail productRetail) {
        return productInfoMapper.updateProductRetail(productRetail);
    }


    /**
     * 新增组合商品信息
     *
     * @param productInfo 商品对象
     */
    public void insertBaseDataProductBundle(ProductInfo productInfo)
    {
        List<ProductBundle> baseDataProductBundleList = productInfo.getBaseDataProductBundleList();
        String id = productInfo.getId();

        if (StringUtils.isNotNull(baseDataProductBundleList))
        {
            List<ProductBundle> list = new ArrayList<ProductBundle>();
            for (ProductBundle baseDataProductBundle : baseDataProductBundleList)
            {
                baseDataProductBundle.setCreateTime(DateUtils.getNowDate());
                //创建人角色
                baseDataProductBundle.setCreateBy(getLoginUser().getUser().getRoles().get(0).getRoleName());
                //创建人编号
                baseDataProductBundle.setCreateById(String.valueOf(getLoginUser().getUserId()));

                baseDataProductBundle.setUpdateTime(DateUtils.getNowDate());
                baseDataProductBundle.setUpdateBy(getLoginUser().getUser().getRoles().get(0).getRoleName());
                //修改人编号
                baseDataProductBundle.setUpdateById(String.valueOf(getLoginUser().getUserId()));

                baseDataProductBundle.setMainProductId(id);

                //随机生成组合商品编号
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String formattedDate = sdf.format(new Date());
                Random random = new Random();
                int randomNumber = 10000000 + random.nextInt(90000000); // 生成8位数随机数
                baseDataProductBundle.setId("110" + formattedDate+randomNumber);

                list.add(baseDataProductBundle);
            }
            if (list.size() > 0)
            {
                productInfoMapper.batchBaseDataProductBundle(list);
            }
        }
    }
}

